package com.liver_cloud.service.doctor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liver_cloud.dao.mybatis.DaoSupport;
import com.liver_cloud.service.mail.MailService;
import com.liver_cloud.util.Consts;
import com.liver_cloud.util.ImageUpLoader;
import com.liver_cloud.util.PageData;

@Service
public class DoctorService {

	@Resource(name = "daoSupport")
	private DaoSupport dao;

	@Autowired
	private MailService mailService;

	public List<PageData> getProvinceCityRegionList() throws Exception {
		// TODO Auto-generated method stub
		List<PageData> provinceList = (List<PageData>) dao.findForList(
				"PatientMapper.getProvinceList", null);
		PageData provinceParam = new PageData();
		provinceParam.put("province", "全部");
		provinceParam.put("provinceId", "");
		provinceList.add(0, provinceParam);
		// 遍历省份集合，得到省份和id，
		for (int i = 0; i < provinceList.size(); i++) {
			// 根据id去city表查询城市集合
			List<PageData> cityList = (List<PageData>) dao.findForList(
					"PatientMapper.getCityList", provinceList.get(i));
			PageData city = new PageData();
			city.put("city", "全部");
			city.put("cityId", "");
			cityList.add(0, city);;
			provinceList.get(i).put("city", cityList);
			// 遍历city集合，得到city和city id
			for (int j = 0; j < cityList.size(); j++) {
				cityList.get(j).put("name", cityList.get(j).get("city"));
				cityList.get(j).remove("city");
				// 根据cityId查询 district 表
				List<PageData> district = (List<PageData>) dao.findForList(
						"PatientMapper.getDistrictList", cityList.get(j));
				PageData districtParam = new PageData();
				districtParam.put("district", "全部");
				districtParam.put("districtId", "");
				district.add(0, districtParam);
				cityList.get(j).put("area", district);
			}
		}
		return provinceList;
	}

	public PageData saveDoctorInfo(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		// 根据userId查询是否已注册
		// 邮箱是否已经注册
		PageData mailUsed = (PageData) dao.findForObject(
				"DoctorMapper.findMail", pd);
		if (mailUsed != null) {
			return null;
		}
		PageData doctor = (PageData) dao.findForObject(
				"DoctorMapper.findDoctor", pd);
		if (doctor != null) {
			// 更新医生基本信息
			dao.update("DoctorMapper.updateDoctorInfo", pd);
			// 更新医生擅长领域,先删除，再插入新的数据
			String doctorId = doctor.get("doctorId").toString();
			pd.put("doctorId", doctorId);
			dao.delete("DoctorMapper.deleteDoctorSkill", pd);
			// 保存擅长领域
			String diagnosis = pd.getString("diagnosisType");
			saveDoctorSkill(doctorId,diagnosis);
			PageData temp = new PageData();
			temp.put("userId", pd.get("userId"));
			saveTransferInfoByCode(pd,doctorId);
			return temp;
		}else{
			// 保存基本信息
			dao.save("DoctorMapper.saveDoctorInfo", pd);
			// 找到注册的doctorId
			String doctorId = (String) dao.findForObject(
					"DoctorMapper.getMyDoctorId", pd);
			// 如果code不为null，则进行医生患者信息绑定
			saveTransferInfoByCode(pd,doctorId);
			PageData result = new PageData();
			result.put("userId", pd.get("userId"));
			// 保存医生擅长领域
			String diagnosis = pd.getString("diagnosisType");
			saveDoctorSkill(doctorId,diagnosis);			
			return result;
		}	
	}
	
	
	/**
	 * 根据code进行医患回话绑定，读取转诊邮件存储内容，保存到对应的表
	 * @param pd
	 * @param doctorId
	 * @throws Exception
	 */
	public void saveTransferInfoByCode(PageData pd,String doctorId) throws Exception{
		// 如果code不为null，则绑定
		if (pd.getString("code") != null && !pd.getString("code").equals("")) {
			//
			String code = pd.getString("code");
			PageData transferInfo = (PageData) dao.findForObject(
					"DoctorMapper.getTransferInfo", code);
			//将之前的医患对话中患者模板设为转诊
			changeTransferPatinetTemplate(transferInfo);
			if (transferInfo != null) {			
				// 建立医患对话，同时在message_info表建立提问的模板内容
				String patientId = transferInfo.get("patientId").toString();
				PageData temp = new PageData();
				temp.put("patientId", patientId);
				temp.put("doctorId", doctorId);
				temp.put("createTime", new Date());
				temp.put("doctorChanged", "1");
				temp.put("patientChanged", "1");
				temp.put("ifTransfer", "1");
				temp.put("transferSucess", "1");
				dao.save("DoctorMapper.insertMessage", temp);
				temp.put("code", code);
				// 将code表used字段改为1
				dao.update("DoctorMapper.updateCodeUsed", temp);
				// 返回新建立的回话Id
				PageData messageInfo = (PageData) dao.findForObject(
						"DoctorMapper.selectMessage", temp);
				String messageId = messageInfo.get("messageId").toString();
				// 在判断医生是否注册成功的接口中更改transferSucess
				// 在message_info表建立提问的模板内容
				String transferContent = transferInfo
						.getString("transferContent");
				if (transferContent != null) {
					JSONArray templateList = JSONArray
							.parseArray(transferContent);
					temp.put("messageId", messageId);
					for (int i = 0; i < templateList.size(); i++) {
						JSONObject objTemp = templateList.getJSONObject(i);
						if(objTemp.get("templateId") != null && objTemp.get("content") != null){
							String templateId = objTemp.get("templateId")
									.toString();
							String content = objTemp.get("content").toString();
							temp.put("templateId", templateId);
							temp.put("content", content);
							dao.save("PatientMapper.savePatientQuestion", temp);							
						}
					}
				}
			}
		}
		
	}
	
	
	/**
	 * 保存医生擅长领域的方法
	 * @param doctorId
	 * @param diagnosis 擅长病症类型字符串，如：1,2,3
	 * @throws Exception 
	 */
	public void saveDoctorSkill(String doctorId, String diagnosis) throws Exception {
		ArrayList<String> diagnosisList = new ArrayList<String>();
		if (diagnosis == null) {
		} else {
			String[] list = diagnosis.split(",");
			if (list == null || list[0].equals("")) {
			} else {
				for (int i = 0; i < list.length; i++) {
					if (!list[i].equals("")) {
						diagnosisList.add(list[i]);
					}
				}
				// 保存擅长领域
				PageData tempSkill = new PageData();
				tempSkill.put("doctorId", doctorId);
				for (int i = 0; i < diagnosisList.size(); i++) {
					tempSkill.put("diagnosisType", diagnosisList.get(i));
					dao.save("DoctorMapper.saveDoctorSkill", tempSkill);
				}
			}
		}
	}
	
	
	

	public PageData saveCertificate(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException,
			FileUploadException {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		ImageUpLoader loader = new ImageUpLoader();
		String url = loader.saveCertificate(request, dao);
		result.put("certificateUrl", url);
		return result;
	}

	public PageData checkCertificate(PageData pd) throws Exception {
		// TODO Auto-generated method stub

		String imageUrl = (String) dao.findForObject(
				"DoctorMapper.getDoctorImage", pd);
		PageData resultInfo = new PageData();
		resultInfo.put("imageUrl", imageUrl);

		PageData checkState = (PageData) dao.findForObject(
				"DoctorMapper.checkCertificate", pd);
		// 该用户未注册医生
		if (checkState == null) {
			resultInfo.put("state", "3");
			return resultInfo;
		}
		String state = checkState.get("di_procedure").toString();
		if ("0".equals(state)) {
			resultInfo.put("state", "0");
			return resultInfo;
		} else if ("1".equals(state)) {
			resultInfo.put("state", "1");
			String ifRecord = checkState.get("ifRecord").toString();
			if ("0".equals(ifRecord)) {
				resultInfo.put("ifRecord", false);
			} else {
				resultInfo.put("ifRecord", true);
			}
			// 根据doctorId将message表中对应的数据transferSucess改为0,同时将code表中used字段改为1
			String doctorId = checkState.get("doctorId").toString();
			dao.update("DoctorMapper.updateTransferStatus", doctorId);
			return resultInfo;
		} else {
			resultInfo.put("state", "2");
			return resultInfo;
		}
	}

	public PageData getDoctorMessage(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		result.put("changed", false);
		result.put("list", "");
		// 根据userId获取mydoctorId
		String mydoctorId = (String) dao.findForObject(
				"DoctorMapper.getMyDoctorId", pd);

		pd.put("userId", mydoctorId);
		// 根据userId去message表查询医生参与的对话
		List<PageData> messageList = (List<PageData>) dao.findForList(
				"DoctorMapper.getDoctorMessage", pd);
		// 医生未发起过对话
		if (messageList == null || messageList.size() == 0) {
			return result;
		}
		result.put("list", messageList);
		//添加消息个数字段
		result.put("messageNum", messageList.size());
		
		// 遍历集合，添加信息
		for (int i = 0; i < messageList.size(); i++) {
			// 医生message是否修改过
			String changed = messageList.get(i).get("changed").toString();
			if ("1".equals(changed)) {
				result.put("changed", true);
				messageList.get(i).put("changed", true);
			}else{
				messageList.get(i).put("changed", false);
			}
			// 病人不再考虑是否是转诊病人
			// 根据patientId查询患者姓名和头像
			String patientId = messageList.get(i).get("patientId").toString();
			PageData patientInfo = (PageData) dao.findForObject(
					"PatientMapper.getPatientInfo", patientId);
			messageList.get(i).put("patientName",
					patientInfo.get("patientName").toString());
			messageList.get(i).put("imageUrl",
					patientInfo.get("imageUrl").toString());
			// 根据patientId在病例表中获取病人的病症
			/*
			 * String diagnosisName = (String) dao.findForObject(
			 * "PatientMapper.getPatientDiagnosis", patientId);
			 * messageList.get(i).put("diagnosisName", diagnosisName);
			 */

			List<String> diagnosisNameList = (List<String>) dao.findForList(
					"PatientMapper.getDgList", patientId);
			messageList.get(i).put("diagnosisNameList", diagnosisNameList);
			// 根据messageId获取病人最近的模板的回复问题及该模板对应的提问内容
			String messageId = messageList.get(i).get("messageId").toString();
			//根据messageId获取solutionId
			PageData solution = 
					(PageData) dao.findForObject("PatientMapper.getSolutionByMessageId", messageId);
			if(solution != null){
				messageList.get(i).put("solutionId", solution.get("solutionId").toString());
			}else{
				messageList.get(i).put("solutionId", "");
			}			
			String replayContent = "";
			String replayId = "";
			String templateContent = "";
			//如果患者有回答，添加回答者的名字
			PageData reply = (PageData) dao.findForObject(
					"PatientMapper.getLastReply", messageId);
			if (reply != null) {
				replayId = reply.get("replayId").toString();
				replayContent = reply.get("replayContent").toString();
				// 根据replyId获取templateContent
				templateContent = (String) dao.findForObject(
						"PatientMapper.getTemplateContent", replayId);
				//根据返回的replierId，replyType查找回答者的姓名
				String replyType = reply.get("replyType").toString();
				if("1".equals(replyType)){
					//表明是助手回答，在助手表中查询助手姓名
					String replierId = reply.get("replierId").toString();
					String assistantName = (String) dao.findForObject("AssistantMapper.getAssistantById", replierId);
					messageList.get(i).put("replier", assistantName);
				}else{
					//在医生表里查询医生姓名
					String replierId = reply.get("replierId").toString();
					String doctorName = (String) dao.findForObject("DoctorMapper.getDoctorName", replierId);
					messageList.get(i).put("replier", doctorName);
			}
				
			} else {
				// 如果没有病人回复，templateContent显示医生提问的问题对应的模板内容
				// 根据messageId查找出最近的questionId
				PageData questionId = (PageData) dao.findForObject(
						"DoctorMapper.getLastQuestionByMessageId", messageId);
				if (questionId == null) {
					// 默认模板第一条的内容
					templateContent = (String) dao
							.findForObject(
									"DoctorMapper.getDefaultTemplateContent",
									messageId);
				} else {
					templateContent = (String) dao.findForObject(
							"DoctorMapper.getTemplateContentByQuestion",
							questionId);
				}

			}
			messageList.get(i).put("replayContent", replayContent);
			messageList.get(i).put("replayId", replayId);
			messageList.get(i).put("templateContent", templateContent);
		}
		return result;
	}

	public PageData updateAndgetPatientQuestionDetail(PageData pd)
			throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		// 根据messageId获取患者id
		String patientId = (String) dao.findForObject(
				"PatientMapper.getPatientId", pd);
		// 根据patientId获取患者姓名，头像
		PageData patientInfo = (PageData) dao.findForObject(
				"PatientMapper.getPatientInfo", patientId);
		result.put("userId", patientId);
		result.put("patientName", patientInfo.get("patientName").toString());
		result.put("imageUrl", patientInfo.get("imageUrl").toString());
		result.put("messageId", pd.get("messageId").toString());
		// 将messageId对应的doctorChanged改为0
		pd.put("changed", "0");
		dao.update("DoctorMapper.updateDoctorChanged", pd);
		// 获取患者病例
		String illnessCaseId = (String) dao.findForObject(
				"PatientMapper.getIllnessCaseId", patientId);
		result.put("illnessCaseId", illnessCaseId);
		// 根据messageId查询messageInfo列表
		List<PageData> messageInfoList = (List<PageData>) dao.findForList(
				"DoctorMapper.getMessageInfoList", pd);
		// 遍历集合
		for (int i = 0; i < messageInfoList.size(); i++) {
			System.out.println(i);
			// 判断是否已经转诊
			String ifTransfer = messageInfoList.get(i).get("templateTransfer")
					.toString();
			if ("1".equals(ifTransfer)) {
				messageInfoList.get(i).put("ifTransfer", true);
			} else {
				messageInfoList.get(i).put("ifTransfer", false);
			}
			// 根据templateId拿到template
			String templateId = messageInfoList.get(i).get("templateId")
					.toString();
					
			//如果是最近病情描述，不允许回答
			String templateContent =  messageInfoList.get(i).get("templateContent")+"";
			messageInfoList.get(i).put("ifDetail", false);	
			messageInfoList.get(i).put("ifCustomDefined", false);
			String template = (String) dao.findForObject(
					"DoctorMapper.getTemplateById", templateId);
			messageInfoList.get(i).put("template", template);
			String messageInfoId = messageInfoList.get(i).get("messageInfoId")
					.toString();
			// 获取该模块对应的问答列表，并按时间降序排列
			List<PageData> questionList = (List<PageData>) dao.findForList(
					"DoctorMapper.getQuestionList", messageInfoId);
			// 遍历问答集合，根据questionId查询reply信息，并插入到问答列表中
			for (int j = 0; j < questionList.size(); j++) {
				String questionId = questionList.get(j).get("questionId")
						.toString();
				PageData reply = (PageData) dao.findForObject(
						"DoctorMapper.getReply", questionId);
				questionList.get(j).put("questioner", "doctor");

				if (reply == null) {
					continue;
				} else {
					reply.put("questioner", "patient");
					// 添加到问答列表
					questionList.add(j + 1, reply);
					j++;
				}

			}
			// 集合倒叙
			List<PageData> resultList = new ArrayList<PageData>();
			if (questionList.size() > 0) {
				for (int j = questionList.size() - 1; j >= 0; j--) {
					resultList.add(questionList.get(j));
				}
			}
			messageInfoList.get(i).put("questionList", resultList);
		}
		
		//
		PageData temp1 = null;
		PageData temp2 = null;
		int tem1 = 0;
		int tem2 = 0;
		for(int i=0;i<messageInfoList.size();i++){
			String templateId = messageInfoList.get(i).get("templateId")
					.toString();
			if("14".equals(templateId)){
				temp1 = messageInfoList.get(i);
				tem1 = i;
			}
		}
		if(temp1 != null){
			messageInfoList.add(0, temp1);
			messageInfoList.get(0).put("ifDetail", true);
			messageInfoList.remove(tem1+1);
		}
		for(int i=0;i<messageInfoList.size();i++){
			String templateId = messageInfoList.get(i).get("templateId")
					.toString();
			if("15".equals(templateId)){
				temp2 = messageInfoList.get(i);
				tem2 = i;
			}
		}
		if(temp2 != null){
			messageInfoList.add(messageInfoList.size(), temp2);
			messageInfoList.get(messageInfoList.size()-1).put("ifCustomDefined", true);
			messageInfoList.remove(temp2);
		}
		
		result.put("list", messageInfoList);
		return result;
	}

	public void saveDoctorQuestion(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		// 根据messageId和templateId 找到messageInfoId
		String messageInfoId = (String) dao.findForObject(
				"DoctorMapper.getMessageInfoId", pd);
		pd.put("messageInfoId", messageInfoId);
		pd.put("createTime", new Date());
		dao.save("DoctorMapper.saveDoctorQuestion", pd);
		// 将messageId对应的patientChanged改为1
		pd.put("changed", "1");
		dao.update("DoctorMapper.updatePatientChanged", pd);
	}

	public void saveSolution(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		pd.put("createTime", new Date());
		// 根据messageId查询是否已经有解决方案了，如果有了，就更新方案
		PageData solution = (PageData) dao.findForObject(
				"DoctorMapper.getSolutionByMessageId", pd);
		if (solution == null) {
			dao.save("DoctorMapper.saveSolution", pd);
		} else {
			// 更新方案
			dao.update("DoctorMapper.updateSolution", pd);
		}
		// 将messageId对应的patientChanged改为1
		pd.put("changed", "1");
		dao.update("DoctorMapper.updatePatientChanged", pd);

	}

	public List<String> getPatientDiagnosisList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		List<String> patientDiagnosisList = (List<String>) dao.findForList(
				"DoctorMapper.getPatientDiagnosisList", pd);
		return patientDiagnosisList;
	}

	public List<PageData> getPatientList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		// 根据医生Id和病症名称获取对应的患者列表
		// 根据userId获取doctorId
		// 找到注册的doctorId
		String doctorId = (String) dao.findForObject(
				"DoctorMapper.getMyDoctorId", pd);
		pd.put("doctorId", doctorId);
		System.out.println(doctorId + pd);
		String diagnosisParam = pd.getString("diagnosisName");
		List<PageData> patientList = new ArrayList<PageData>();
		if (diagnosisParam != null && !diagnosisParam.equals("")) {
			// 判断diagnosisParam是几个病症
			String[] diagList = diagnosisParam.split(",");
			ArrayList<String> diagnosisList = new ArrayList<String>();
			for (int i = 0; i < diagList.length; i++) {
				if (!diagList[i].equals("")) {
					diagnosisList.add(diagList[i]);
				}
			}
			pd.put("diagnosisList", diagnosisList);
			patientList = (List<PageData>) dao.findForList(
					"DoctorMapper.getPatientList", pd);
		} else {
			// 查询全部患者
			patientList = (List<PageData>) dao.findForList(
					"DoctorMapper.getPatientListConditonTwo", pd);
		}
		// 根据patientId获取对应的病症名称
		for (int i = 0; i < patientList.size(); i++) {
			// 填充数据，昵称，头像，病症名称
			String patientId = patientList.get(i).get("patientId").toString();
			List<PageData> diagnosisName = (List<PageData>) dao.findForList(
					"DoctorMapper.getPatientDiagnosisName", patientId);
			PageData patientInfo = (PageData) dao.findForObject(
					"PatientMapper.getPatientInfo", patientId);
			patientList.get(i).put("patientName",
					patientInfo.getString("patientName"));
			patientList.get(i).put("imageUrl",
					patientInfo.getString("imageUrl"));
			patientList.get(i).put("userId", patientId);
			patientList.get(i).put("diagnosisNameList", diagnosisName);
			// 获取illnessCaseId
			String illnessCaseId = (String) dao.findForObject(
					"PatientMapper.getIllnessCaseId", patientId);
			patientList.get(i).put("illnessCaseId", illnessCaseId);
		}

		return patientList;
	}

	public PageData getTransferCode() throws Exception {
		// TODO Auto-generated method stub

		boolean ifExist = true;
		String code = "";
		while (ifExist) {
			code = UUID.randomUUID().toString().replaceAll("-", "")
					.substring(0, 6);
			// 根据code查询是否已经存在过了
			PageData codeInfo = (PageData) dao.findForObject(
					"DoctorMapper.selectCode", code);
			if (codeInfo == null) {
				ifExist = false;
			}
		}
		PageData result = new PageData();
		result.put("code", code);
		return result;
	}

	public void saveAndsendTransferMail(JSONObject param) throws Exception {
		// TODO Auto-generated method stub
		mailService.saveAndsendTransferMail(param);
		// 将转诊的信息保存到md_code_transfer表
		PageData pd = new PageData();
		// 解析jsonObject
		JSONObject paramObj = param.getJSONObject("param");
		// 转诊的内容集合

		JSONArray templateList = paramObj.getJSONArray("templateList");
		String messageId = paramObj.getString("messageId");
		String mailTo = paramObj.getString("mailTo");
		String patientId = paramObj.getString("patientId");
		String code = paramObj.getString("code");
		String transferContent = templateList.toJSONString();
		pd.put("patientId", patientId);
		pd.put("code", code);
		pd.put("transferContent", transferContent);
		pd.put("messageId", messageId);
		dao.save("DoctorMapper.saveTranserInfo", pd);

		// 根据messageId和templateList，将该病人对应的模块更改为转发，转诊成功后再修改患者模块
		/*pd.put("messageId", messageId);
		for (int i = 0; i < templateList.size(); i++) {
			JSONObject objTemp = templateList.getJSONObject(i);
			String templateId = objTemp.get("templateId").toString();
			pd.put("templateId", templateId);
			dao.update("PatientMapper.updateTemplateTransfer", pd);
		}*/
	}
	
	/**
	 * 医生根据邀请码注册成功或者医生接受转诊患者后，根据transferInfo信息将患者之前的模板设为已转诊
	 * @param transferInfo
	 * @throws Exception 
	 */
	public void changeTransferPatinetTemplate(PageData transferInfo) throws Exception{
		if (transferInfo != null) {
		String messageBeforeId = transferInfo.get("messageId").toString();
		String transferContentList = transferInfo
				.getString("transferContent");
		JSONArray templateListContent = JSONArray
				.parseArray(transferContentList);
		PageData tempPd = new PageData();
		tempPd.put("messageId", messageBeforeId);
		for (int i = 0; i < templateListContent.size(); i++) {
				JSONObject objTemp = templateListContent.getJSONObject(i);
				if(objTemp.get("templateId") != null){
				String templateId = objTemp.get("templateId").toString();
				tempPd.put("templateId", templateId);
				dao.update("PatientMapper.updateTemplateTransfer", tempPd);				
			}
		}
		}	
	}
	
	public void adoptTransferPatient(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		String adopt = pd.getString("adopt");
		String doctorId = pd.getString("doctorId");
		if ("1".equals(adopt) && doctorId != null && !doctorId.equals("")) {
			// 读取code表信息，建立回话
			String code = pd.getString("code");
			PageData transferInfo = (PageData) dao.findForObject(
					"DoctorMapper.getTransferInfo", code);
			//将之前的医患对话中患者模板设为转诊
			changeTransferPatinetTemplate(transferInfo);
			if (transferInfo != null) {
				// 建立医患对话，同时在message_info表建立提问的模板内容
				String patientId = transferInfo.get("patientId").toString();
				PageData temp = new PageData();
				temp.put("patientId", patientId);
				temp.put("doctorId", doctorId);
				temp.put("createTime", new Date());
				temp.put("doctorChanged", "1");
				temp.put("patientChanged", "1");
				temp.put("ifTransfer", "1");
				temp.put("transferSucess", "0");
				dao.save("DoctorMapper.insertMessage", temp);
				temp.put("code", code);
				// 将code表used字段改为1
				dao.update("DoctorMapper.updateCodeUsed", temp);
				// 返回新建立的回话Id
				PageData messageInfo = (PageData) dao.findForObject(
						"DoctorMapper.selectMessage", temp);
				String messageId = messageInfo.get("messageId").toString();
				// 在message_info表建立提问的模板内容
				String transferContent = transferInfo
						.getString("transferContent");
				if (transferContent != null) {
					JSONArray templateList = JSONArray
							.parseArray(transferContent);
					temp.put("messageId", messageId);
					for (int i = 0; i < templateList.size(); i++) {
						JSONObject objTemp = templateList.getJSONObject(i);
						if(objTemp.get("templateId") != null && objTemp.get("content") != null){
							String templateId = objTemp.get("templateId")
									.toString();
							String content = objTemp.get("content").toString();
							temp.put("templateId", templateId);
							temp.put("content", content);
							dao.save("PatientMapper.savePatientQuestion", temp);							
						}
					}
				}
			}
			// 将codeTransfer表中的usered改为1
			dao.update("DoctorMapper.updateCodeUsed", pd);
		} else if ("0".equals(adopt)) {
			// 点击拒绝，直接将code标记为已用
			dao.update("DoctorMapper.updateCodeUsed", pd);
		}
		// 如果点击接受，但是doctorId为null或为空字符串，则不做任何操作

	}

	public List<PageData> getCertificateUrlList() throws Exception {
		// TODO Auto-generated method stub
		return (List<PageData>) dao.findForList(
				"DoctorMapper.getCertificateUrlList", null);
	}

	public void deleteCertificate(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		pd.put("certificateUrl", "");
		dao.update("DoctorMapper.deleteCertificate", pd);
	}

	public void savePassThrough(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		dao.update("DoctorMapper.updatePassThrough", pd);
	}

	public PageData getDoctorMessageChanged(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		result.put("ifChanged", false);
		//根据userId查询doctorId
		String doctorId = (String) dao.findForObject(
				"DoctorMapper.getMyDoctorId", pd); 
		List<PageData> messageChanged =
				(List<PageData>) dao.findForList("DoctorMapper.getDoctorMessageChanged", doctorId);
		if(messageChanged != null && messageChanged.size()>0){
			result.put("ifChanged", true);
		}
		return result;
	}

	public PageData getHospitalList(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData result = new PageData();
		List<String> hospitalList = 
				(List<String>) dao.findForList("DoctorMapper.getHospitalList", pd);
		result.put("hospitalList", hospitalList);
		return result;
	}

	public PageData getDoctorInfo(PageData pd) throws Exception {
		// TODO Auto-generated method stub
		PageData doctorInfo = (PageData) dao.findForObject("DoctorMapper.getDoctorInfoDesc", pd);
		
		String province = (String) dao.findForObject("DoctorMapper.getProvince", doctorInfo);
		String city = (String) dao.findForObject("DoctorMapper.getCity", doctorInfo);
		String region = (String) dao.findForObject("DoctorMapper.getRegion", doctorInfo);
		String department = (String) dao.findForObject("DoctorMapper.getDepartment", doctorInfo);
		String profession = (String) dao.findForObject("DoctorMapper.getprofession", doctorInfo);
		doctorInfo.put("city", city+"");
		if("市辖区".equals(city)||"县".equals(city)){
			doctorInfo.put("city", province+"");
			}
		doctorInfo.put("region", region+"");
		doctorInfo.put("province", province+"");
		doctorInfo.put("department", department+"");
		//根据professionId查找职称，
		doctorInfo.put("profession", profession+"");
		doctorInfo.put("description", doctorInfo.get("description")+"");
		List<String> doctorSkill = 
				(List<String>) dao.findForList("DoctorMapper.getDoctorSkill", doctorInfo);
		doctorInfo.put("skillList", doctorSkill);		
		return doctorInfo;
	}

	public List<PageData> getAssistantList(PageData pd) throws Exception {
		List<PageData> assistantList = 
				(List<PageData>) dao.findForList("DoctorMapper.getAssistantList", pd);
		//添加patientNum//管理病人的个数，labelList管理的病症标签，answerNum回答的问题
		for(int i=0;i<assistantList.size();i++){
			//根据assistantId查询管理病人个数
			String num = 
					(String) dao.findForObject("AssistantMapper.getPatientNum", assistantList.get(i));
			assistantList.get(i).put("patientNum", num);
			//根据doctorId和管理的patientId，查询并添加管理的病症标签
			assistantList.get(i).put("doctorId", pd.get("doctorId"));
			List<String> labelList = 
					(List<String>) dao.findForList("AssistantMapper.getPatientTitle", assistantList.get(i));
			assistantList.get(i).put("labelList", labelList);
			//添加回答问题的个数
			String answerNum = 
					(String) dao.findForObject("AssistantMapper.getAnswerNum", assistantList.get(i));
			assistantList.get(i).put("answerNum", answerNum);	
		}
		
		return assistantList;
	}
	
	//获取助手回答的问题列,前提是助手已经回答过了，未回答的不在里面显示
	public List<PageData> getAssistantAnswerList(PageData pd) throws Exception {
		//根据adRelationId医生助手关系id，assistantId查询其负责的问题
		//获取messageId，solutionId，patientName，imageUrl，患者病例标签，问题及回答createTime:回答时间
		List<PageData> patientList = 
				(List<PageData>) dao.findForList("AssistantMapper.getAnswerPatientList", pd);
		//添加solutionId,患者病例标签diagnosisNameList
		for(int i=0;i<patientList.size();i++){
			//根据messageId查询是否有解决方案
			String solutionId = 
					(String) dao.findForObject("AssistantMapper.getSolutionId", patientList.get(i));
			patientList.get(i).put("solutionId", solutionId);
			//根据patientId添加diagnosisNameList
			List<String> diagnosisNameList = 
					(List<String>) dao.findForList("PatientMapper.getDiagnosisNameList", patientList.get(i));
			patientList.get(i).put("diagnosisNameList", diagnosisNameList);
			//根据messageId添加最新的问答模块,并返回回答者身份，回答时间，回答者,以最新的问答为主
			//获取最新的问题
			PageData question = 
					(PageData) dao.findForObject("AssistantMapper.getLastQuestion", patientList.get(i));
			patientList.get(i).put("templateContent", "");
			if(question != null){
				patientList.get(i).put("templateContent",question.get("templateContent"));
				patientList.get(i).put("createTime",question.get("questTime"));
				PageData reply = 
						(PageData) dao.findForObject("AssistantMapper.getReply", question);
				if(reply==null){
					patientList.get(i).put("replyContent","");
					patientList.get(i).put("replyName","");
				}else{
					patientList.get(i).put("replyContent",reply.get("replyContent"));
					patientList.get(i).put("createTime",reply.get("createTime"));
					String replyType = reply.get("replyType")+"";
					if("0".equals(replyType)){
						patientList.get(i).put("replyName","我");
					}else{
						String idTemp = pd.getString("assistantId");
						String assistantName = 
								(String) dao.findForObject("AssistantMapper.getAssitantName", idTemp);
						patientList.get(i).put("replyName",assistantName);
					}
					
				}
				
			}else{
				//如果患者仅仅是加载了几个模板，没有问问题，则显示添加的模板
				//需进一步完善
				
			}
			
		}
		
		
		return patientList;
	}
	
	
	//修改模板
	public void sendMessage(PageData pd) {
		// TODO Auto-generated method stub
		
	}

	public PageData getAllotPatientList(PageData pd) throws Exception {
		// 根据type判断搜索类型：1：已分配；2：未分配
		String type = pd.getString("type");
		String patientTitel = pd.getString("patientTitel")+"";
		PageData result = new PageData();
		if("1".equals(type)){
			//搜索已分配的患者
			if("0".equals(patientTitel)){
				//搜索所有标签的患者
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.getAllotedPatient", pd);
				//遍历集合，添加patientTitelList
				addPatientTitel(patientList,pd);
				result.put("num", patientList.size());
				result.put("patientList", patientList);
				return result;
			}else{
				//搜索符合标签的患者
				String[] titelArray = patientTitel.split(",");
				pd.put("titelArray", titelArray);
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.getAllotedPatientByCondition", pd);
				//遍历集合，添加patientTitelList
				addPatientTitel(patientList,pd);
				result.put("num", patientList.size());
				result.put("patientList", patientList);
				return result;				
			}			
		}else{
			//搜索未分配的患者
			if("0".equals(patientTitel)){
				//搜索所有未分配的患者，0代表所有标签
				List<PageData> patientList=
						(List<PageData>) dao.findForList("DoctorMapper.getUnAllotedPatient", pd);
				addPatientTitel(patientList,pd);
				result.put("num", patientList.size());
				result.put("patientList", patientList);
				return result;
			}else{
				//搜索符合标签的，所有未分配的患者
				String[] titelArray = patientTitel.split(",");
				pd.put("titelArray", titelArray);
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.getUnAllotedPatientByCondition", pd);	
				addPatientTitel(patientList,pd);
				result.put("num", patientList.size());
				result.put("patientList", patientList);
				return result;
			}			
		}
	}
	
	
	public List<PageData> addPatientTitel(List<PageData> patientList,PageData pd) throws Exception{
		//遍历集合，添加patientTitelList
		for(int i=0;i<patientList.size();i++){
			//根据doctorId和patientId获取医生给患者自定义的标签
			patientList.get(i).put("doctorId", pd.get("doctorId"));
			List<String> patientTitelList = 
					(List<String>) dao.findForList("DoctorMapper.getDefinedTitel", patientList.get(i));
			patientList.get(i).put("patientTitelList", patientTitelList);					
		}		
		return patientList;
		
	}
	
	public List<PageData> searchAllotPatient(PageData pd) throws Exception {
		//根据searchType分类：1：搜索已分配；2：搜索未分配 
		String searchType = pd.getString("searchType");
		String patientTitel = pd.getString("patientTitel");//0代表所搜所有的标签，否则按出入的条件搜索
		if("1".equals(searchType)){
			if("0".equals(patientTitel)){
				//在已分配患者中，忽略标签，直接搜索
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.searchPatientIgnorTitel", pd);
				//添加医生给患者自定义的标签
				addPatientTitel(patientList,pd);
				return patientList;
			}else{
				//搜索符合标签的患者
				String[] titelArray = patientTitel.split(",");
				pd.put("titelArray", titelArray);
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.searchPatientByTitel", pd);
				//添加医生给患者自定义的标签
				addPatientTitel(patientList,pd);
				return patientList;
			}			
		}else{
			//在未分配患者中搜索
			if("0".equals(patientTitel)){
				//在未分配患者中，忽略标签，直接搜索
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.searchUnAllotedPatientIgnorTitel", pd);
				//添加医生给患者自定义的标签
				addPatientTitel(patientList,pd);
				return patientList;				
			}else{				
				List<PageData> patientList = 
						(List<PageData>) dao.findForList("DoctorMapper.searchUnAllotedPatientByTitel", pd);
				//添加医生给患者自定义的标签
				addPatientTitel(patientList,pd);
				return patientList;	
			
			}
			
		}

	}
	
	
	public void savePatientTitel(PageData pd) throws Exception {
		//第一步：删除隶属于该医生的患者的所有标签
		dao.delete("DoctorMapper.deletePatientTitel", pd);		
		//第二步：将新传入的标签插入
		String titelId = pd.getString("titelId");
		if(titelId==null||"".equals(titelId)){
			return;
		}
		String[] titelArray = titelId.split(",");
		//获取医患关系id
		String dpId = 
				(String) dao.findForObject("DoctorMapper.getDpId", pd);
		if(dpId==null||"".equals(dpId)){
			return;
		}
		pd.put("dpId", dpId);
		for(int i=0;i<titelArray.length;i++){
			pd.put("patientTitel", titelArray[i]);
			dao.save("DoctorMapper.savePatientTitel", pd);
		}		
	}

	public List<PageData> getDefinePatientTitel(PageData pd) throws Exception {
		
		return (List<PageData>) dao.findForList("DoctorMapper.getDefinePatientTitel", pd);
	}
	
	//分配患者给助手
	public void saveAndDistributePatient(PageData pd) throws Exception {
		//distributeType;1:重新分配已分配的患者；2：将未分配的患者分配给助手
		String distributeType = pd.getString("distributeType");
		String patientId = pd.getString("patientId");
		if(patientId==null){
			return;
		}
		String[] patientIdArray = patientId.split(",");
		pd.put("patientIdArray", patientIdArray);
		List<PageData> messageIdList = 
				(List<PageData>) dao.findForList("DoctorMapper.getMessageList", pd);
		String adRelationId = pd.getString("adRelationId");
		if("1".equals(distributeType)){
			//如果是重新分配，则
			//第一步：先将messageId在md_assistant_patient表中的transer为0，delet为0的列更改为已转给其他助手,即tansfer为1，同时
			//添加时间transfer_date.第二步：
			for(int i=0;i<messageIdList.size();i++){
				messageIdList.get(i).put("transferDate", new Date());
				dao.update("AssistantMapper.updateTransferPatient", messageIdList.get(i));
				//向md_assistant_patient表插入数据
				messageIdList.get(i).put("adRelationId", adRelationId);
				dao.save("AssistantMapper.savePatient", messageIdList.get(i));				
			}			
		}else if("2".equals(distributeType)){
			//在助手患者表中插入新信息，转诊时可一次性转诊多个病人
			//第一步：根据传入的patientId和doctorId查询出所有的messageId，然后向md_assistant_patient表中插入数据					
			//遍历集合，向md_assistant_patient表插入数据
			for(int i=0;i<messageIdList.size();i++){
				messageIdList.get(i).put("adRelationId", adRelationId);
				dao.save("AssistantMapper.savePatient", messageIdList.get(i));
			}
			
		}
		
		
	}

	
}









